import sun.reflect.generics.tree.Tree;

public class Solution897 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode increasingBST(TreeNode root) {
        if (root==null){
            return null;
        }
        TreeNode treeNodeL=increasingBST(root.left);
        TreeNode treeNodeR=increasingBST(root.right);
        root.right=treeNodeR;
        if (treeNodeL==null){
            return root;
        }
        TreeNode node=treeNodeL;
        while (node.right!=null){
            node=node.right;
        }
        node.right=root;
        root.left=null;
        return treeNodeL;
    }

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(5,new TreeNode(3,new TreeNode(2,new TreeNode(1),null),new TreeNode(4)),new TreeNode(6,null,new TreeNode(8,new TreeNode(7),new TreeNode(9))));
        System.out.println(new Solution897().increasingBST(treeNode).val);
    }

}
